package com.zhkj.txg.module.order.vm

import android.app.Application
import android.os.CountDownTimer
import android.text.TextUtils
import android.util.Log
import androidx.lifecycle.MutableLiveData
import com.google.gson.Gson
import com.zhkj.lib.base.BaseViewModel
import com.zhkj.lib.base.QueryShippingResponse
import com.zhkj.lib.http.HttpResponse
import com.zhkj.lib.http.ViewModelSubscribeListener
import com.zhkj.lib.utils.AccountManager
import com.zhkj.lib.utils.RxBus
import com.zhkj.lib.utils.SPUtil
import com.zhkj.txg.base.CustomApplication
import com.zhkj.txg.module.order.entity.*
import com.zhkj.txg.module.order.model.OrderManager
import com.zhkj.txg.module.order.ui.OrderListRefreshEvent
import com.zhkj.txg.utils.PayResult
import io.reactivex.android.schedulers.AndroidSchedulers

class OrderViewModel(application: Application) : BaseViewModel(application) {
    private var timer: CountDownTimer? = null
    private val orderManager = OrderManager()
    private val orderSubmitLiveData = MutableLiveData<HttpResponse<OrderSubmitResponse>>()
    private val payResultLiveData = MutableLiveData<PayResult>()
    private val orderListRefreshLiveData = MutableLiveData<OrderListRefreshEvent>()
    val orderDetailLiveData = MutableLiveData<HttpResponse<OrderDetailResponse>>()
    val payOrderLiveData = MutableLiveData<HttpResponse<OrderPayResponse>>()
    val orderLiveData = MutableLiveData<HttpResponse<OrderSubmitDetailResponse>>()
    val orderGroupLiveData = MutableLiveData<HttpResponse<OrderSubmitGroupResponse>>()
    val orderListLiveData = MutableLiveData<HttpResponse<OrderListResponse>>()
    val orderCancelLiveData = MutableLiveData<HttpResponse<OrderCancelResponse>>()
    val orderShippingLiveData = MutableLiveData<HttpResponse<OrderShippingResponse>>()
    val queryShippingLiveData = MutableLiveData<HttpResponse<QueryShippingResponse>>()
    val receiveOrderLiveData = MutableLiveData<HttpResponse<ReceiveOrderResponse>>()
    val countDownLiveData: MutableLiveData<Long> = MutableLiveData()
    val deleteOrderLiveData = MutableLiveData<HttpResponse<ReceiveOrderResponse>>()

    override fun onCleared() {
        super.onCleared()
        if (timer != null) timer?.cancel()
    }

    fun startCountDown() {
        if (timer != null) {
            timer?.cancel()
            timer = null
        }
        val millisInFuture = (orderDetailLiveData.value?.response?.data?.progress?.end_time ?: 0) * 1000
        timer = object : CountDownTimer(millisInFuture, 1000) {
            override fun onFinish() {
                countDownLiveData.value = 0
                orderDetailLiveData.value?.response?.data?.progress?.end_time = 0
            }

            override fun onTick(millisUntilFinished: Long) {
                orderDetailLiveData.value?.response?.data?.progress?.end_time = millisUntilFinished / 1000
                countDownLiveData.value = millisUntilFinished / 1000
            }
        }
        timer?.start()
    }

    /**
     * 订单列表页使用到的参数
     */
    var orderType: String = ""
    private val numb = 20
    var page = 1
        private set

    /**
     * 立即购买 - 获取订单详情
     */
    /* fun buyNow(token: String, goodsId: Int, number: Int, specId: Int = 0, shareId: Int = 0) {
         val listener = object : ViewModelSubscribeListener<OrderSubmitDetailResponse>(orderLiveData) {
             override fun onSuccess(resp: OrderSubmitDetailResponse) {
                 resp.data?.let { order ->
                     order.useCouponTotalPrice = order.goodsTotalFee
                     order.cartList.forEach { it.useCouponTotalPrice = it.shopTotalFee }
                 }
                 super.onSuccess(resp)
             }
         }
         val buyNow = orderManager.buyNow(token, goodsId, number, specId, shareId, listener)
         dispose.add(buyNow)
     }*/

    /**
     * 立即购买 - 获取订单详情(切换地址）
     */
    fun buyNow(token: String, goodsId: Int, number: Int, shopId: Int) {
        val listener = object : ViewModelSubscribeListener<OrderSubmitDetailResponse>(orderLiveData) {
            override fun onSuccess(resp: OrderSubmitDetailResponse) {
                resp.data?.let { order ->
                    order.useCouponTotalPrice = order.goodsTotalFee
                    order.cartList.forEach { it.useCouponTotalPrice = it.shopTotalFee }
                }
                super.onSuccess(resp)
            }
        }
        val buyNow = orderManager.buyNow(token, goodsId, number, shopId, listener)
        dispose.add(buyNow)
    }

    /**
     * 拼团购买- 获取订单详情
     */
    fun groupBuyNow(
        token: String,
        goodsId: Int,
        number: Int,
        specId: Int = 0,
        group_id: Int = 0,
        type: Int = 1,
        shareId: Int = 0
    ) {
        val listener = object : ViewModelSubscribeListener<OrderSubmitGroupResponse>(orderGroupLiveData) {
            override fun onSuccess(resp: OrderSubmitGroupResponse) {
                resp.data?.let { order ->
                    order.goods?.useCouponTotalPrice = order.goodsTotalFee
                }
                super.onSuccess(resp)
            }
        }
        val groupBuyNow = orderManager.groupBuyNow(
            token,
            goodsId,
            number,
            specId,
            group_id,
            type,
            shareId,
            listener
        )
        dispose.add(groupBuyNow)
    }

    /**
     * 提交订单详情
     */
    fun submitOrder(map: Map<String, String>): MutableLiveData<HttpResponse<OrderSubmitResponse>> {
        val listener = ViewModelSubscribeListener(orderSubmitLiveData)
        orderLiveData.value?.response?.data?.let {
            val cartListString = formatOrderRequestParam(it.cartList)

//            val shopId = SPUtil.getInstance().getString(AccountManager.SHOP_ID) ?: ""
//            val map = hashMapOf("shop_id" to shopId)
//            map["address_id"] = it.address?.id.toString()
//            map["cart_list"] = cartListString

        }
        val submitOrder = orderManager.submitOrder(map, listener)
        dispose.add(submitOrder)
        return orderSubmitLiveData
    }

    /**
     *  拼团：提交订单支付
     */
    fun submitGroupOrder(
        token: String,
        type: Int,
        group_id: Int = 0,
        user_note: String,
        shareId: Int = 0
    ): MutableLiveData<HttpResponse<OrderSubmitResponse>> {
        val listener = ViewModelSubscribeListener(orderSubmitLiveData)
        orderGroupLiveData.value?.response?.data?.let {
            val submitOrder = orderManager.submitGroupOrder(
                token,
                type,
                it.goods?.goodsId,
                it.goods!!.goodsNumber,
                it.goods!!.itemId,
                group_id,
                it.address?.id ?: 0,
                it.goods.selectCoupon?.id ?: 0,
//                couponId,
                user_note,
                shareId,
                listener
            )
            dispose.add(submitOrder)
        }
        return orderSubmitLiveData
    }

    /**
     * 订单支付
     */
    fun payOrder(
        token: String,
        orderId: Long,
        orderSignNumber: String,
        payType: String,
        uiPosition: Int = 0,
        isGroup: Boolean = false
    ) {
        val listener = object : ViewModelSubscribeListener<OrderPayResponse>(payOrderLiveData) {
            override fun onSuccess(resp: OrderPayResponse) {
                resp.data.uiPosition = uiPosition
                super.onSuccess(resp)
            }
        }
//        val payOrder =
//            if (!isGroup) orderManager.payOrder(token, orderId, orderSignNumber, payType, listener)
//            else orderManager.groupPayOrder(token, orderId, orderSignNumber, payType, listener)
//        dispose.add(payOrder)
    }

    /**
     * 订单支付
     */
    fun payOrder(map: Map<String, String>) {
        val listener = object : ViewModelSubscribeListener<OrderPayResponse>(payOrderLiveData) {
            override fun onSuccess(resp: OrderPayResponse) {
//                resp.data.uiPosition = uiPosition
                super.onSuccess(resp)
            }
        }
        val payOrder = orderManager.payOrder(map, listener)
        dispose.add(payOrder)
    }

    /**
     * 拼团：订单支付
     */
    fun groupPayOrder(
        token: String,
        orderId: Long,
        orderSignNumber: String,
        payType: String,
        uiPosition: Int = 0
    ) {
        val listener = object : ViewModelSubscribeListener<OrderPayResponse>(payOrderLiveData) {
            override fun onSuccess(resp: OrderPayResponse) {
                resp.data.uiPosition = uiPosition
                super.onSuccess(resp)
            }
        }
        val payOrder = orderManager.groupPayOrder(token, orderId, orderSignNumber, payType, listener)
        dispose.add(payOrder)
    }

    /**
     * 购物车结算-进入订单结算页
     */
    fun cartBuy(cartIds: MutableList<String>, addressId: Int = 0) {
        val json = Gson()
        Log.e("TAG", "=====cartIds=${json.toJson(cartIds)}====${addressId}")
        val listener = object : ViewModelSubscribeListener<OrderSubmitDetailResponse>(orderLiveData) {
            override fun onSuccess(resp: OrderSubmitDetailResponse) {
                resp.data?.let { order ->
                    order.useCouponTotalPrice = order.goodsTotalFee
                    order.cartList.forEach { it.useCouponTotalPrice = it.shopTotalFee }
                }
                super.onSuccess(resp)
            }
        }

        val buyNow = orderManager.cartBuy(cartIds, addressId, CustomApplication.getShopId().toString(), listener)
        dispose.add(buyNow)
    }

    /**
     * 订单列表
     */
    fun orderList(token: String, restart: Boolean = false) {
        val listener = object : ViewModelSubscribeListener<OrderListResponse>(orderListLiveData) {
            override fun onSuccess(resp: OrderListResponse) {
                resp.hasMore = resp.data.size >= numb
                resp.loadMore = page > 1
                super.onSuccess(resp)
                page += 1
            }
        }
        if (restart) page = 1
        orderManager.orderList(token, page, numb, orderType, listener)
    }

    /**
     * 拼团：订单列表
     */
    fun groupOrderList(token: String, restart: Boolean = false) {
        val listener = object : ViewModelSubscribeListener<OrderListResponse>(orderListLiveData) {
            override fun onSuccess(resp: OrderListResponse) {
                resp?.data?.let {
                    for (order in it) {
                        if (order.goods != null) {
                            order.totalNumber = 0
                            for (good in order.goods) {
                                order.totalNumber += good.goodsNum
                                order.people?.let {
                                    good.people = it
                                }
                            }
                        }
                    }
                }
                resp.hasMore = resp.data.size >= numb
                resp.loadMore = page > 1
                super.onSuccess(resp)
                page += 1
            }
        }
        if (restart) page = 1
        orderManager.groupOrderList(token, page, numb, orderType, listener)
    }

    /**
     * 支付结果
     */
    fun payResult(): MutableLiveData<PayResult> {
        val payResult = RxBus.toObservable(PayResult::class.java)
            .subscribeOn(AndroidSchedulers.mainThread()).subscribe({
                payResultLiveData.value = it
            }, {
                it.printStackTrace()
                payResultLiveData.value = PayResult(false, it.message ?: "")
            })
        dispose.add(payResult)
        return payResultLiveData
    }

    /**
     * 取消订单
     * isGroup : 是否拼团订单
     */
    fun cancelOrder(token: String, orderId: Long, uiPosition: Int, isGroup: Boolean = false) {
        val listener =
            object : ViewModelSubscribeListener<OrderCancelResponse>(orderCancelLiveData) {
                override fun onSuccess(resp: OrderCancelResponse) {
                    resp.uiPosition = uiPosition
                    super.onSuccess(resp)
                }
            }
        val orderCancel =
            if (!isGroup) orderManager.orderCancel(token, orderId, listener)
            else orderManager.groupOrderCancel(token, orderId, listener)
        dispose.add(orderCancel)
    }

    /**
     * 获取订单详情
     */
    fun orderDetail(
        token: String,
        orderId: Long,
        isGroup: Boolean = false
    ): MutableLiveData<HttpResponse<OrderDetailResponse>> {
        val listener = ViewModelSubscribeListener(orderDetailLiveData)
        val orderDetail =
            if (!isGroup) orderManager.orderDetail(token, orderId, listener)
            else orderManager.groupOrderDetail(token, orderId, listener)
        dispose.add(orderDetail)
        return orderDetailLiveData
    }

    /**
     * 获取订单物流顶部详情
     */
    fun orderShippingDetail(token: String, orderId: Long, isGroup: Boolean = false) {
        val listener =
            object : ViewModelSubscribeListener<OrderShippingResponse>(orderShippingLiveData) {
                override fun onSuccess(resp: OrderShippingResponse) {
                    super.onSuccess(resp)
                    resp.data?.let {
                        queryShipping(token, it.shippingNo, it.shippingCode)
                    }
                }
            }
        val orderShippingDetail =
            if (!isGroup) orderManager.orderShippingDetail(token, orderId, listener)
            else orderManager.groupShippingDetail(token, orderId, listener)
        dispose.add(orderShippingDetail)
    }

    /**
     * 查询订单物流详情
     */
    fun queryShipping(token: String, shippingNo: String, shippingCode: String) {
        val listener = ViewModelSubscribeListener(queryShippingLiveData)
        val queryShipping = orderManager.queryShipping(token, shippingNo, shippingCode, listener)
        dispose.add(queryShipping)
    }

    /**
     * 删除订单
     */
    fun deleteOrder(orderId: Long, uiPosition: Int = -1, isGroup: Boolean = false) {
        val listener = object : ViewModelSubscribeListener<ReceiveOrderResponse>(deleteOrderLiveData) {
            override fun onSuccess(resp: ReceiveOrderResponse) {
                resp.uiPosition = uiPosition
                super.onSuccess(resp)
            }
        }
        val deleteOrder = if (!isGroup) orderManager.deleteOrder(AccountManager.getToken(), orderId, listener)
        else orderManager.deleteGroupOrder(AccountManager.getToken(), orderId, listener)
        dispose.add(deleteOrder)
    }

    /**
     * 确认收货
     */
    fun receiveOrder(token: String, uiPosition: Int, orderId: Long, isGroup: Boolean = false) {
        val listener =
            object : ViewModelSubscribeListener<ReceiveOrderResponse>(receiveOrderLiveData) {
                override fun onSuccess(resp: ReceiveOrderResponse) {
                    resp.uiPosition = uiPosition
                    super.onSuccess(resp)
                }
            }
        val receiveOrder =
            if (!isGroup) orderManager.receiveOrder(token, orderId, listener)
            else orderManager.groupReceiveOrder(token, orderId, listener)
        dispose.add(receiveOrder)
    }

    /**
     * 订单列表页刷新观察者
     */
    fun orderListStatusSubscribe(): MutableLiveData<OrderListRefreshEvent> {
        val subscribe = RxBus.toObservable(OrderListRefreshEvent::class.java)
            .observeOn(AndroidSchedulers.mainThread()).subscribe({
                orderListRefreshLiveData.value = it
            }, { it.printStackTrace() })
        dispose.add(subscribe)
        return orderListRefreshLiveData
    }

    fun formatOrderRequestParam(cartList: MutableList<CartEntity>): String {
        val list = mutableListOf<SubmitOrderFormatEntity>()
        for (cart in cartList) {
            if (cart.goodsList.size > 0) {
                // 拼接cartIds
                val buildString = buildString {
                    loop@ for (product in cart.goodsList) {
                        if (product.cartId.isEmpty()) break@loop
                        else append(product.cartId).append(",")
                    }
                    if (isNotEmpty()) deleteCharAt(lastIndex)
                }
                val goods = cart.goodsList[0]
                val entity = SubmitOrderFormatEntity(
                    cart.shopId,
                    cart.orderDesc ?: "",
                    cart.selectCoupon?.id ?: 0,
                    goods.goodsId,
                    goods.goodsNumber,
                    if (TextUtils.isEmpty(goods.itemId)) 0 else goods.itemId.toInt(),
                    buildString
                )
                list.add(entity)
            }
        }
        return Gson().toJson(list)
    }
}